<?php 
class Master extends CI_Controller {
	
	function master()
	{
		parent::__construct();
		$this->load->library('session');
		$this->load->library('form_validation');
		$this->load->library('encrypt');
                $this->load->model('mmaster');
                $this->load->model('mglobal');
		#$this->is_logged_in();
		#$this->mjadwal->saveLog();
	}
	
	function is_logged_in()
	{
		$is_logged_in = $this->session->userdata('is_logged_in');
		if(!isset($is_logged_in) || $is_logged_in != true)
		{
			redirect('/login');
		}		
	}
	
	function usermanagement($proses="",$id="")
	{
		$data['template'] = "shell/smooth";
                $data['users']    = $this->mmaster->getUser();
                $data['main_view']      = 'f-users';
		$data['proses']		= $proses;
		$data['id']	= $id;
		
		$data['data'] = array("name"=>"","email"=>"","username"=>"","password"=>"");
		if($proses<>"" && $id<>""){
		    $getdata = $this->mmaster->getUser($id);
		    foreach($getdata as $r){
			$data['data']['name'] 		= $r->name;
			$data['data']['email'] 		= $r->email;
			$data['data']['username'] 	= $r->username;
			$data['data']['password'] 	= $r->password;
		    }
		}
		#inisialisasi elemen form yang harus diisi
		$this->form_validation->set_rules('name', 'Nama', 'required');
		$this->form_validation->set_rules('username', 'Username', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_vemail_check');
		
		$this->form_validation->set_error_delimiters('<li>','</li>');
		$this->form_validation->set_message('required', 'Kolom <b>%s</b> harus diisi.');
		$this->form_validation->set_message('valid_email', 'Kolom <b>%s</b> harus diisi dengan alamat email yang benar.');
                
		if ($this->form_validation->run() != FALSE){
			// masukkan data di sini
			$this->mmaster->saveUser($id);
			$this->session->set_flashdata('message', 'Data Berhasil dimasukkan');
			redirect('/master/usermanagement');
		}	
		
                $hasil = "";
                $this->load->view($data['template'],$data);
	}
        
        
        function distributor($proses="",$id="")
	{
		$data['template'] = "shell/smooth";
                $data['users']    = $this->mmaster->getDistributor();
                $data['main_view']      = 'f-distributor';
		$data['proses']		= $proses;
		$data['id']	= $id;
		
		$data['data'] = array("name"=>"","distributor_add"=>"","distributor_id"=>"");
		if($proses<>"" && $id<>""){
		    $getdata = $this->mmaster->getDistributor($id);
		    foreach($getdata as $r){
			$data['data']['name'] 		        = $r->distributor_name;
			$data['data']['distributor_add'] 	= $r->distributor_add;
			$data['data']['distributor_id'] 	= $r->distributor_id;
		    }
		}
		
		#inisialisasi elemen form yang harus diisi
		$this->form_validation->set_rules('name', 'Nama', 'required');
		$this->form_validation->set_rules('distributor_add', 'Dstributor Add', 'required');
		
		$this->form_validation->set_error_delimiters('<li>','</li>');
		$this->form_validation->set_message('required', 'Kolom <b>%s</b> harus diisi.');
                
		if ($this->form_validation->run() != FALSE){
			// masukkan data di sini
			$this->mmaster->saveDistributor($id);
			$this->session->set_flashdata('message', 'Data Berhasil dimasukkan');
			redirect('/master/distributor');
		}	
		
                $hasil = "";
                $this->load->view($data['template'],$data);
	}
        
        function agents($proses="",$id="")
	{
		$data['template'] = "shell/smooth";
		//$data['users']    = $this->mmaster->getAgents();
		$data['main_view']      = 'f-agents';
		$data['proses']		= $proses;
		$data['id']	= $id;
		
		$arr = array( 'agent_status', 'identity', 'o_location', 'o_type', 'b_focus' );
		
		foreach( $arr as $combo )
		{
			$query = $this->mmaster->getComboData( $combo );
			
			$i = 0;
			
			foreach( $query->result() as $r )
			{
				$data[ 'data' ][ $combo ][ 'member_value' ][ $i ] = $r->member_value;
				$data[ 'data' ][ $combo ][ 'member_display' ][ $i ] = $r->member_display;
				$i++;
			}
		}
		
		
		$query = $this->mmaster->getRecord( 't_mtr_province' );
		$i = 0;
		foreach( $query->result() as $r )
		{
			$data[ 'data' ][ 'province' ][ $i ] = $r->province_name;
			$i++;
		}
		
		$usr_id = $this->session->userdata( 'username' );
		$query = $this->mmaster->getTerritory( $usr_id );
		$row = $query->row();
		$result = '';
		
		if( $query->num_rows() == 0 )
			$data[ 'data' ][ 'path' ] = 'You are not a cluster responsible person';
		else
		{
			$parent_id = $row->parent_id;
			$result = $row->territory_name;
			$territory_id = $row->territory_id;
			$data[ 'data' ][ 'territory_id' ] = $territory_id;
			$t_id = $territory_id;
			
			while( $parent_id != 0 )
			{	
				$query = $this->mmaster->getTerritory( $parent_id );
				$row = $query->row();
				$parent_id = $row->parent_id;
				$result = $row->territory_name.' -> '.$result;
				$territory_id = $row->territory_id;				
			}
			
			$data[ 'data' ][ 'path' ] = $result;
		}

		$query = $this->mmaster->getMaintainName();
		$i = 0;
		
		foreach( $query->result() as $r )
		{
			$data[ 'data' ][ 'username' ][ $i ] = $r->user_name;
			$data[ 'data' ][ 'pos' ][ $i ] = $this->mmaster->getPosition( $r->user_id )->row()->user_group_name;
			$i++;
		}
		/*$data['data'] = array("name"=>"","address"=>"","teritory_id"=>"");
		if($proses<>"" && $id<>""){
		    $getdata = $this->mmaster->getAgents($id);
		    foreach($getdata as $r){
			$data['data']['name'] 		= $r->agent_name;
			$data['data']['address'] 	= $r->address;
			$data['data']['teritory_id'] 	= $r->teritory_id;
		    }
		}*/
		
		#inisialisasi elemen form yang harus diisi
		/*
		$this->form_validation->set_rules('name', 'Nama', 'required');
		$this->form_validation->set_rules('address', 'Alamat', 'required');
                $this->form_validation->set_rules('teritory_id', 'Territory', 'required');
		
		$this->form_validation->set_error_delimiters('<li>','</li>');
		$this->form_validation->set_message('required', 'Kolom <b>%s</b> harus diisi.');
                
		if ($this->form_validation->run() != FALSE){
			// masukkan data di sini
			$this->mmaster->saveAgents($id);
			$this->session->set_flashdata('message', 'Data Berhasil dimasukkan');
			redirect(base_url()."index.php/master/agents");
		}*/			
                $hasil = "";
                $this->load->view($data['template'],$data);
	}
	
        public function readuser() {
		echo json_encode( $this->mmaster->getUser() );
	}
	
	function pagemanagement($act="",$page="")
	{
		$data['template'] = "shell/smooth";
                $data['main_view']     = 'f-pages';
                $this->load->view($data['template'],$data);
	}
	
	
	
	private function initializeArray( $name, $proses="" )
	{
		if( $name == 'agent' )
		{
			$data['template'] = "shell/smooth";
			$data['main_view'] = 'f-agents';
			$data['proses'] = $proses;
			$data[ 'agent_name' ] = '';
			$data[ 'agent_address' ] = '';
			$data[ 'agent_city' ] = '';
			$data[ 'agent_province' ] = '';
			$data[ 'agent_id' ] = '';
			$data[ 'agent_zip_code' ] = '';
			$data[ 'agent_phone_no' ] = '';
			$data[ 'agent_mdn_evo' ] = ''; 
			$data[ 'maintain_name' ] = ''; 
			$data[ 'is_school' ] = ''; 	
			$data[ 'majority_num' ] = '';
			$data[ 'faculty_num' ] = '';
			$data[ 'student_num' ] = '';
			$data[ 'teacher_num' ] = '';		
			$data[ 'employee_num' ] = ''; 
			$data[ 'agent_location' ] = ''; 
			$data[ 'agent_type' ] = ''; 
			$data[ 'agent_business_focus' ] = ''; 
			$data[ 'agent_website' ] = ''; 
			$data[ 'pic_name' ] = '';
			$data[ 'pic_phone' ] = '';
			$data[ 'pic_address' ] = '';
			$data[ 'pic_city' ] = '';
			$data[ 'pic_province' ] = '';
			$data[ 'pic_zip_code' ] = '';
			$data[ 'pic_identity_type' ] = '';
			$data[ 'pic_identity_no' ] = '';
			$data[ 'pic_birth_place' ] = '';
			$data[ 'pic_birth_date' ] = '';
			$data[ 'pic_job_position' ] = '';
			$data[ 'pic_smartfren_no' ] = '';
			$data[ 'pic_mobile_no' ] = '';
			$data[ 'pic_email' ] = '';
		}
		else
		{
			$data['template'] = "shell/smooth";
			$data['main_view'] = "f-outlets";
			$data[ 'branding_status' ] = '';
			$data[ 'full_branding' ] = '';
			$data[ 'contract_end' ] = '';
			$data[ 'value' ] = '';
			$data[ 'owner_name' ] = '';
			$data[ 'owner_gender' ] = '';
			$data[ 'owner_birth_place' ] = '';
			$data[ 'owner_birth_date' ] = '';
			$data[ 'owner_religion' ] = '';
			$data[ 'owner_email' ] = '';
			$data[ 'owner_phone' ] = '';
			$data[ 'owner_identity_type' ] = '';
			$data[ 'owner_identity_number' ] = '';
			$data[ 'outbond' ] = '';
			$data[ 'outlet_id' ] = '';
			$data[ 'outlet_status' ] = '';
			$data[ 'outlet_type' ] = '';
			$data[ 'outlet_size' ] = '';
			$data[ 'outlet_location' ] = '';
			$data[ 'outlet_employee_number' ] = '';
			$data[ 'outlet_lifetime' ] = '';
			$data[ 'outlet_ownership' ] = '';
			$data[ 'outlet_smart_no' ] = '';
			$data[ 'outlet_business_focus' ] = '';
			$data[ 'outlet_customer_type' ] = '';
			$data[ 'outlet_size_of_business' ] = '';
			$data[ 'outlet_expansion_package' ] = '';
			$data[ 'outlet_join_lajang' ] = '';
			$data[ 'outlet_lajang_package' ] = '';
			$data[ 'outlet_lajang_is_reorder' ] = '';
			$data[ 'outlet_address' ] = '';
			$data[ 'outlet_name' ] = '';
			$data[ 'outlet_city' ] = '';
			$data[ 'outlet_province' ] = '';
			$data[ 'outlet_post_code' ] = '';
			$data[ 'outlet_phone' ] = '';
			$data[ 'outlet_eload_number' ] = '';
			$data[ 'outlet_business_structure' ] = '';
			$data[ 'front_type' ] = '';
			$data[ 'front_name' ] = '';
			$data[ 'front_birth_place' ] = '';
			$data[ 'front_birth_date' ] = '';
			$data[ 'front_identity_type' ] = '';
			$data[ 'front_identity_no' ] = '';
			$data[ 'front_religion' ] = '';
			$data[ 'front_work' ] = '';
			$data[ 'front_marital' ] = '';
			$data[ 'front_address' ] = '';
			$data[ 'front_city' ] = '';
			$data[ 'front_province' ] = '';
			$data[ 'front_zip' ] = '';
			$data[ 'front_mdn' ] = '';
			$data[ 'front_remark' ] = '';
			$data[ 'bank_name' ] = '';
			$data[ 'bank_branch' ] = '';
			$data[ 'bank_account_name' ] = '';
			$data[ 'bank_account_number' ] = '';
		}
		
		return $data;
	}
	
	private function fillData( $arr )
	{		
		foreach( $arr as $combo )
		{
			$query = $this->mmaster->getComboData( $combo );
			$i = 0;
			foreach( $query->result() as $r )
			{
				$data[ 'data' ][ $combo ][ 'member_value' ][ $i ] = $r->member_value;
				$data[ 'data' ][ $combo ][ 'member_display' ][ $i ] = $r->member_display;
				$i++;
			}
		}
		
		/**************************** ISI COMBO PROVINCE *****************************/
		$query = $this->mmaster->getRecord( 't_mtr_province' );
		$i = 0;
		foreach( $query->result() as $r )
		{
			$data[ 'data' ][ 'province' ][ 'member_value' ][ $i ] = $r->province_id;
			$data[ 'data' ][ 'province' ][ 'member_display' ][ $i ] = $r->province_name;
			$i++;
		}
				
		/*******************************ISI TERRITORY PATH******************************/
		$result = $this->mmaster->getTerritoryPath( $this->session->userdata( 'username' ), 'cluster' );
		$data[ 'data' ][ 'tr_path' ][ 'member_display' ] = $result[ 'path' ];
		$data[ 'data' ][ 'tr_path' ][ 'member_value' ] = $result[ 'territory_id' ];
		
		
		/************* ISI COMBO FIELD NAME PADA MAINTAINED BY *************************/
		$query = $this->mmaster->getMaintainName();
		$i = 0;
		foreach( $query->result() as $r )
		{
			$data[ 'data' ][ 'maintain_name' ][ 'member_display' ][ $i ] = $r->user_name;
			$data[ 'data' ][ 'maintain_name' ][ 'member_value' ][ $i ] = $r->user_id;
			$data[ 'data' ][ 'maintain_name' ][ 'pos' ][ $i ] = $this->mmaster->getPosition( $r->user_id )->row()->user_group_name;
			$i++;
		}
		
		return $data;
	}
	
	
	/* @author: Willy Halim Dinata
	 * @function: controller dari halaman outlet
	 */
	function outlets( $param1="", $param2="", $param3=""  )
	{
		$data = $this->initializeArray( 'outlet' );
		/****************************** ISI COMBO**********************************/
		$arr = array( 'building', 'gender', 'religion', 'identity', 'o_status', 'o_type', 'o_size', 
						'o_location', 'o_ownership', 'b_structure', 'b_focus', 'b_size', 'c_type', 
						'l_package', 'e_package', 'position', 'full_branding', 'outbond', 'front_type', 
						'marital' );
		
		$fillData = $this->fillData( $arr );
		$data = array_merge( $data, $fillData );
		
		if( $param1 == 'frontliners' )
		{	
			$frontlinerData = $this->frontliner( $param2, $param3 );
			$data = array_merge( $data, $frontlinerData );
		}
		else if( $param1 == 'bank' )
		{
			$bankData = $this->bank( $param2, $param3 );
			$data = array_merge( $data, $bankData );
		}
		else
		{
			if( $param1 == 'update' )
			{
				$updateData = $this->updateOutlet( $param2 );
				$data = array_merge( $data, $updateData );
			}
			
			/******************************** VALIDATION *************************/
			$this->form_validation->set_rules( 'name_owner', 'Owner Name', 'required|max_length[30]' );
			$this->form_validation->set_rules( 'outlet_name', 'Outlet Name', 'required|max_length[255]' );
			$this->form_validation->set_rules( 'address', 'Outlet Address', 'required|max_length[255]' );
			$this->form_validation->set_rules( 'city', 'Outlet City', 'required|max_length[100]' );
			$this->form_validation->set_rules( 'province', 'Province', 'required|max_length[100]' );
			$this->form_validation->set_rules( 'post_code', 'Post Code', 'numeric|max_length[10]' );
			$this->form_validation->set_rules( 'employee_nume', 'Employee Number', 'numeric|max_length[10]' );
			$this->form_validation->set_rules( 'birth_place', 'Birth Place', 'max_length[50]' );
			$this->form_validation->set_rules( 'birth_date', 'Birth Date', 'required' );
			$this->form_validation->set_rules( 'email', 'Email', 'valid_email|max_length[50]' );
			$this->form_validation->set_rules( 'phone', 'Phone', 'integer|max_length[20]' );
			$this->form_validation->set_rules( 'identity_number', 'Identity Number', 'integer|max_length[50]' );
			$this->form_validation->set_rules( 'branding_value', 'Branding Value', 'numeric' );
			$this->form_validation->set_rules( 'identity_number', 'Identity Number', 'integer|max_length[50]' );
			
			
			if( $param1 == 'approve' )
			{
				$this->moutlets->updateOutlet( $param2 );
				$this->session->set_flashdata('message', 'Outlet sudah disetujui');
				
				redirect('/master/outlets');
			}
			
			if( $this->form_validation->run() != FALSE )
			{
				if( $param1 == 'update' )
				{
					$this->moutlets->saveOutlets( $param2, $param1 );
					$this->session->set_flashdata('message', 'Data Outlet Berhasil diubah');
				}
				else
				{
					$this->moutlets->saveOutlets( '', $param1 );
					$this->session->set_flashdata('message', 'Data Outlet Berhasil dimasukkan');
				}
				
				redirect('/master/outlets');
			}	
		}
		
		$this->load->view($data['template'],$data);
	}
	
	
	private function updateOutlet( $id )
	{
		$outlet = $this->db->get_where( 't_mtr_outlet', array( 'outlet_id' => $id ) )->row(); 
		$outlet_data = $this->db->get_where( 't_mtr_outlet_data', array( 'outlet_id' => $id ) )->row();
		$outlet_branding = $this->db->get_where( 't_mtr_outlet_branding', array( 'outlet_id' => $id ) )->row();				
		$outlet_owner = $this->db->get_where( 't_mtr_outlet_owner', array( 'outlet_id' => $id ) )->row();
				
		if( $outlet_data != null && $outlet != null )
		{
			$data[ 'building' ] = $outlet_data->outlet_building;
			$data[ 'maintain_name' ] = $this->mmaster->getMaintainName( $outlet->territory_id );
			
			if( $outlet_branding != null )
			{
				$data[ 'branding_status' ] = $outlet_branding->branding_status;
				$data[ 'full_branding' ] = $outlet_branding->full_branding_by;
				$data[ 'contract_end' ] = $outlet_branding->contract_end;
				$data[ 'value' ] = $outlet_branding->branding_value;
			}
			
			if( $outlet_owner != null )
			{
				$data[ 'owner_name' ] = $outlet_owner->owner_name;
				$data[ 'owner_gender' ] = $outlet_owner->owner_gender;
				$data[ 'owner_birth_place' ] = $outlet_owner->owner_birth_place;
				$data[ 'owner_birth_date' ] = $outlet_owner->owner_birth_date;
				$data[ 'owner_religion' ] = $outlet_owner->owner_religion;
				$data[ 'owner_email' ] = $outlet_owner->owner_email;
				$data[ 'owner_phone' ] = $outlet_owner->owner_phone;
				$data[ 'owner_identity_type' ] = $outlet_owner->owner_identity_type;
				$data[ 'owner_identity_number' ] = $outlet_owner->owner_identity_number;
			}
			
			$data[ 'outbond' ] = $this->mmaster->getOutbondCallerName( $outlet->outbond_caller_id );
			$data[ 'outlet_id' ] = $outlet->outlet_id;
			$data[ 'outlet_status' ] = $outlet_data->outlet_status;
			$data[ 'outlet_type' ] = $outlet_data->outlet_type;
			$data[ 'outlet_size' ] = $outlet_data->outlet_size;
			$data[ 'outlet_location' ] = $outlet_data->outlet_location;
			$data[ 'outlet_employee_number' ] = $outlet_data->outlet_employee_number;
			$data[ 'outlet_lifetime' ] = $outlet_data->outlet_lifetime;
			$data[ 'outlet_ownership' ] = $outlet_data->outlet_ownership;
			$data[ 'outlet_smart_no' ] = $outlet_data->outlet_smart_no;
			$data[ 'outlet_business_focus' ] = $outlet_data->outlet_business_focus;
			$data[ 'outlet_customer_type' ] = $outlet_data->outlet_customer_type;
			$data[ 'outlet_size_of_business' ] = $outlet_data->outlet_size_of_business;
			$data[ 'outlet_expansion_package' ] = $outlet_data->outlet_expansion_package;
			$data[ 'outlet_join_lajang' ] = $outlet_data->outlet_join_lajang;
			$data[ 'outlet_lajang_package' ] = $outlet_data->outlet_lajang_package;
			$data[ 'outlet_lajang_is_reorder' ] = $outlet_data->outlet_lajang_is_reorder;
			$data[ 'outlet_address' ] = $outlet->address;
			$data[ 'outlet_name' ] = $outlet->outlet_name;
			$data[ 'outlet_city' ] = $outlet->city;
			$data[ 'outlet_province' ] = $outlet->province_id;
			$data[ 'outlet_post_code' ] = $outlet->post_code;
			$data[ 'outlet_phone' ] = $outlet->phone;
			$data[ 'outlet_eload_number' ] = $outlet->eload_number;
			$data[ 'outlet_business_structure' ] = $outlet->business_structure;
		}
		
		return $data;
	}
	
	
	private function bank( $proses, $id )
	{		
		if( $proses == 'update' )
		{
			$bank = $this->mmaster->getBanks( $id );
			
			$data[ 'bank_name' ] = $bank->bank_name;
			$data[ 'bank_branch' ] = $bank->bank_branch;
			$data[ 'bank_account_name' ] = $bank->bank_account_name;
			$data[ 'bank_account_number' ] = $bank->bank_account_number;
		}
		
		$this->form_validation->set_rules( 'bank_name', 'Bank Name', 'required|alpha|max_length[30]' );
		
		if( $this->form_validation->run() != FALSE )
		{
			$this->mmaster->saveBank( $id, $proses );
			
			if( $proses == "new" )
				$this->session->set_flashdata('message', 'Data Bank Berhasil dimasukkan');
			else
				$this->session->set_flashdata('message', 'Data Bank Berhasil diubah');
			
			redirect(base_url()."index.php/master/outlets/update");
		}
		
		return $data;
	}
	
	private function frontliner( $proses, $id )
	{
		if( $proses == "update" )
		{
			$front = $this->moutlets->getFrontliners( $id );
			
			$data[ 'front_type' ] = $front->frontliner_type;
			$data[ 'front_name' ] = $front->frontliner_name;
			$data[ 'front_birth_place' ] = $front->frontliner_birth_place;
			$data[ 'front_birth_date' ] = $front->frontliner_birth_date;
			$data[ 'front_identity_type' ] = $front->frontliner_identity_type;
			$data[ 'front_identity_no' ] = $front->frontliner_identity_no;
			$data[ 'front_religion' ] = $front->frontliner_religion;
			$data[ 'front_work' ] = $front->frontliner_work_experience;
			$data[ 'front_marital' ] = $front->frontliner_marital_status;
			$data[ 'front_address' ] = $front->frontliner_address;
			$data[ 'front_city' ] = $front->frontliner_city;
			$data[ 'front_province' ] = $front->frontliner_province_id;
			$data[ 'front_zip' ] = $front->frontliner_zip_code;
			$data[ 'front_mdn' ] = $front->frontliner_mdn_smartfren;
			$data[ 'front_remark' ] = $front->frontliner_remark;
		}
		
		$this->form_validation->set_rules( 'front_name', 'Frontliner Name', 'required|alpha|max_length[30]' );
		
		if( $this->form_validation->run() != FALSE )
		{
			$this->moutlets->saveFrontliners( $id, $proses );
			
			if( $proses == "new" )
				$this->session->set_flashdata('message', 'Data Frontliner Berhasil dimasukkan');
			else
				$this->session->set_flashdata('message', 'Data Frontliner Berhasil diubah');
			
			redirect(base_url()."index.php/master/outlets/update");
		}
		
		return $data;
	}
	
	/*
	function vemail_check($str)
	{
		$where = array("email"=>$str);
		if($this->uri->segment(4) <> "") $where = array("email"=>$str,"username !="=>$this->uri->segment(4));
		$v = $this->mglobal->showdata('username','t_users',$where,'dblokal');
		if ($v <> "")
		{
			$this->form_validation->set_message('vemail_check', 'Email <b>'. $str .'</b> sudah memiliki akun.');
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}*/
}